package com.haredot.service.impl;

import com.haredot.dto.UserLoginDTO;
import com.haredot.entity.Student;
import com.haredot.entity.Teacher;
import com.haredot.entity.User;
import com.haredot.mapper.StudentMapper;
import com.haredot.mapper.TeacherMapper;
import com.haredot.service.LoginService;
import com.haredot.utils.MD5Utils;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class LoginServiceImpl implements LoginService {

    @Resource
    private StudentMapper studentMapper ;

    @Resource
    private TeacherMapper teacherMapper ;

    @Override
    public R<User> loginByRole(UserLoginDTO userLoginDTO) {

        User user = null ;
        if ("teacher".equals(userLoginDTO.getRole())) {
            user = teacherMapper.selectByPrimaryKey(userLoginDTO.getUsername());
        }else if ("student".equals(userLoginDTO.getRole())) {
            user = studentMapper.selectByPrimaryKey(userLoginDTO.getUsername());
        }else{
            return R.<User>fail().data(Map.of("role", "认证失败、角色错误"));
        }

        if (user == null) {
            return R.<User>fail().data(Map.of("id", "认证失败、" + ("teacher".equals(userLoginDTO.getRole()) ? "工号": "学号") +"错误"));
        }
        // 比较密码 是否一致
        if (!MD5Utils.md5(userLoginDTO.getPassword()).equals(user.getPassword())) {
            return R.<User>fail().data(Map.of("password", "认证失败、密码错误"));
        }

        // 返回认证后的用户
        return R.<User>ok().data(user);
    }
}
